import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'
import remark from 'remark'
import html from 'remark-html'
var toHast = require('mdast-util-to-hast')

const prefix = '/boboan.github.io'
const postsDirectory = path.join(process.cwd(), 'posts')

export function getSortedPostsData(pageNum = 1, pageSize = 10, tag) {
  // Get file names under /posts
  const fileNames = fs.readdirSync(postsDirectory)
  let allPostsData = fileNames.map(fileName => {
    // Remove ".md" from file name to get id
    const id = fileName.replace(/\.md$/, '')

    // Read markdown file as string
    const fullPath = path.join(postsDirectory, fileName)
    const fileContents = fs.readFileSync(fullPath, 'utf8')

    // Use gray-matter to parse the post metadata section
    const matterResult = matter(fileContents)
    // Combine the data with the id
    return {
      id,
      ...matterResult.data,
      image: path.resolve(`${prefix}/posts`, matterResult.data.image)
    }
  })
  if (tag) {
    allPostsData = allPostsData.filter(post => post.tags.includes(tag))
  }
  // Sort posts by date
  allPostsData.sort((a, b) => {
    if (a.date < b.date) {
      return 1
    } else {
      return -1
    }
  })
  return { allPostsData: allPostsData.slice((pageNum - 1) * pageSize, pageNum * pageSize), total: allPostsData.length }
}

export function getAllPostIds() {
  const fileNames = fs.readdirSync(postsDirectory)
  return fileNames.map(fileName => {
    return {
      params: {
        id: fileName.replace(/\.md$/, '')
      }
    }
  })
}

export async function getPostData(id) {
  const fullPath = path.join(postsDirectory, `${id}.md`)
  const fileContents = fs.readFileSync(fullPath, 'utf8')

  // Use gray-matter to parse the post metadata section
  const matterResult = matter(fileContents)

  // Use remark to convert markdown into HTML string
  const processedContent = await remark()
    .use(html)
    .process(matterResult.content)
  const contentHtml = processedContent.toString()

  // Combine the data with the id and contentHtml
  return {
    id,
    contentHtml,
    ...matterResult.data
  }
}

export function getAllTags() {
  const fileNames = fs.readdirSync(postsDirectory)
  const tags = {}
  fileNames.forEach(fileName => {
    // Remove ".md" from file name to get id
    const id = fileName.replace(/\.md$/, '')

    // Read markdown file as string
    const fullPath = path.join(postsDirectory, fileName)
    const fileContents = fs.readFileSync(fullPath, 'utf8')

    // Use gray-matter to parse the post metadata section
    const matterResult = matter(fileContents)
    // Combine the data with the id
    matterResult.data?.tags?.forEach?.(tag => {
      tags[tag] = 1
    })
  })
  return Object.keys(tags)
}
